<template>
  <a-form ref="formRef" :model="searchForm" :hideRequiredMark="true">
    <a-row :gutter="20">
      <a-col :span="4">
        <a-form-item name="portValue">
          <a-select ref="select" v-model:value="searchForm.appType" @change="handleChange" placeholder="请选择端口">
            <a-select-option v-for="item in ports" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="5" :offset="1" :lg="5" :xs="11">
        <a-range-picker
          v-model:value="time"
          style="width: 100%"
          :ranges="ranges"
          show-time
          format="YYYY/MM/DD HH:mm:ss"
          @change="panelChange"
        />
      </a-col>

      <a-col :span="4" :offset="1" :lg="5" :xs="10">
        <a-form-item name="keyword">
          <a-input v-model:value="searchForm.keyword" placeholder="请输入搜索内容"></a-input>
        </a-form-item>
      </a-col>
      <a-col :span="2" :offset="1"> <a-button type="primary" @click="search" class="d-a-center">搜索</a-button></a-col>
    </a-row>
  </a-form>
  <a-button type="primary" style="margin-bottom: 30px" @click="add" v-has="{ a: $route, b: 2 }" class="d-a-center">新增</a-button>
  <!-- 列表 -->
  <a-table
    :columns="columns"
    :data-source="list"
    bordered
    :loading="loading"
    :pagination="pagination"
    @change="handleTableChange"
    :scroll="{ y: 540 }"
  >
    <template #appType="{ record }">
      <a-tag>{{ record.appType == 1 ? '护士端' : '用户端' }}</a-tag>
    </template>
    <template #systemType="{ record }">
      <a-tag :color="record.systemType == 1 ? 'pink' : 'cyan'">{{ record.systemType == 0 ? 'android' : 'ios' }}</a-tag>
    </template>
    <template #updateType="{ record }">
      <a-tag :color="record.updateType == 1 ? 'success' : 'error'">{{ record.updateType == 0 ? '强制' : '不强制' }}</a-tag>
    </template>
    <!-- <template #operation="{ record }">
        <a-button type="link" @click="look(record.key)">查看</a-button>
      </template> -->
  </a-table>
  <a-modal :visible="visible" @cancel="cancel" @ok="save" width="70%" :footer="null">
    <a-tag color="error" class="warning">当前版本号一定要大于已经上线的APP版本号，否则更新将会失败！！！</a-tag>
    <div style="margin-top: 20px">
      <a-tag color="error">1.热更新的时候记得把manifest.json中的应用版本号改了哦！！！</a-tag>
    </div>
    <div style="margin-top: 20px">
      <a-tag color="error">2.隐私政策中的版本号也要修改！！！</a-tag>
    </div>

    <a-divider></a-divider>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="App" name="appType">
        <a-row>
          <a-col :span="12">
            <a-radio-group v-model:value="form.appType">
              <a-radio :value="1"><a-tag color="processing">护士端</a-tag> </a-radio>
              <a-radio :value="2"><a-tag color="processing">用户端</a-tag> </a-radio>
            </a-radio-group>
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="操作系统" name="systemType">
        <a-row>
          <a-col :span="12">
            <a-checkbox-group v-model:value="value" name="checkboxgroup" :options="options" />
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="版本号" name="number">
        <a-row>
          <a-col :span="6">
            <a-input
              style="width: 100%"
              placeholder="请输入版本号(当前版本号一定要大于线上的版本号！！！)"
              v-model:value="form.number"
            ></a-input>
          </a-col>
        </a-row>
      </a-form-item>

      <!-- <a-form-item label="更新地址" name="value">
        <a-row>
          <a-col :span="12">
             <a-input placeholder="请输入更新地址" v-model:value="value1" addon-before="https://hushixiaolu.com/"/>
          </a-col>
        </a-row>
      </a-form-item> -->

      <a-form-item label="安装包地址" name="address">
        <a-row>
          <a-col :span="18">
            <a-input placeholder="安装包名称" :disabled="true" v-model:value="form.address" :addon-before="baseUrl" addon-after=".wgt" />
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="是否强制升级" name="value">
        <a-row>
          <a-col :span="12">
            <a-radio-group v-model:value="form.updateType" name="radioGroup">
              <a-radio :value="0">是</a-radio>
              <a-radio :value="1">否</a-radio>
            </a-radio-group>
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="更新内容" name="value">
        <a-row>
          <a-col :span="12">
            <tinymce v-if="visible" ref="editor" :value="form.content" @input="tinymceInput"></tinymce>
          </a-col>
        </a-row>
      </a-form-item>
    </a-form>
    <a-row>
      <a-col :span="4" :offset="8">
        <a-button type="primary" @click="save" class="d-a-center">保存</a-button>
      </a-col>
      <a-col :span="4" :offset="1">
        <a-button type="info" @click="cancel" class="d-a-center">关闭</a-button>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs, h, toRef } from 'vue'
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import tinymce from '@/components/common/tinymce/tinymce'
import { Modal, message } from 'ant-design-vue'
import { useModal } from '@/hooks'
import { addVersion, selectAllVersion, getNewVersion } from '@/api/setting/index'
export default {
  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    tinymce
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const formRef = ref('')
    // const form = reactive({
    //   updateType: 1,
    // });
    // 表单验证
    const rules = {
      appType: [
        {
          required: true,
          message: '请选择'
        }
      ],
      number: [
        {
          required: true,
          message: '我天，版本号你都能忘！！！',
          trigger: 'change'
        }
      ],
      address: [{ required: true, message: '安装包地址忘记输入了亲', trigger: 'blur' }]
    }
    const data = reactive({
      list: [],
      visible: false,
      value: ['0', '1'],
      // baseUrl: "https://hushixiaolu.com/", //安装包地址路径
      baseUrl: 'http://120.26.232.8:7009/userWeb/', //安装包地址路径
      searchForm: {},
      form: {
        updateType: 0,
        number: ''
      }
    })

    watch([() => data.form.appType, () => data.form.number], ([newVal1, newVal2], [oldVal1, oldVal2]) => {
      // 当param1或param2变化时，更新result
      // result.value = newVal1 + newVal2;
      if (newVal1) {
        data.form.address = newVal1 == 1 ? 'nurse' + newVal2 : 'user' + newVal2
      } else {
        data.form.address = ''
      }
    })
    // 选择时间
    const panelChange = (date, dateString) => {
      data.searchForm.startTime = dateString[0]
      data.searchForm.endTime = dateString[1]
    }
    //   端口列表
    const ports = reactive([
      {
        name: '全部',
        id: ''
      },
      {
        name: '护士端',
        id: 1
      },
      {
        name: '用户端',
        id: 2
      }
    ])

    const loading = ref(true) //表格的加载
    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })

    const columns = [
      {
        title: 'App',
        dataIndex: 'id',
        className: 'table',
        align: 'center'
      },
      {
        title: '端口',
        dataIndex: 'appType',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'appType'
        }
      },
      {
        title: '系统',
        dataIndex: 'systemType',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'systemType'
        }
      },
      {
        title: '版本号',
        dataIndex: 'number',
        className: 'table',
        align: 'center'
        // sorter:(a, b)=> {
        //    return parseFloat(a.number) - parseFloat(b.number)
        // }
      },
      {
        title: '更新时间',
        dataIndex: 'createdAt',
        className: 'table',
        align: 'center',
        sorter: (a, b) => {
          const aTime = new Date(a.createdAt).getTime()
          const bTime = new Date(b.createdAt).getTime()
          return aTime - bTime
        }
      },
      {
        title: '更新包地址',
        dataIndex: 'address',
        className: 'table',
        align: 'center'
      },

      {
        title: '是否强制升级',
        dataIndex: 'updateType',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'updateType'
        }
      },
      {
        title: '更新内容',
        dataIndex: 'content',
        className: 'table',
        align: 'center'
      }
      // {
      //   title: "操作",
      //   className: "table",
      //   align: "center",
      //   slots: {
      //     customRender: "operation",
      //   },
      // },
    ]

    const options = [
      {
        label: '苹果系统',
        value: '1'
      },
      {
        label: '安卓系统',
        value: '0'
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 是否是排序?但是如果点击了排序又点击了排序……如何
      console.log(Object.keys(sorter).length)
      if (Object.keys(sorter).length == 0) {
        // 请求列表接口
        init()
      }
    }
    // const look=(key)=>{
    //   data.visible=true
    // }

    const search = () => {
      page.current = 1
      loading.value = true
      init()
    }
    const tinymceInput = e => {
      data.form.content = e
    }
    const save = async () => {
      // data.form.appType = 1; //护士端更新
      data.form.updateCount = 1 //更新次数

      if (!data.value) {
        message.error('请选择更新的系统!!!')
        return
      }
      formRef.value.validate().then(async res => {
        // data.form.address = data.baseUrl + data.form.address + '.wgt'
        let formData = {
          ...data.form,
          address: data.baseUrl + data.form.address + '.wgt'
        }
        console.log(formData, '表单内容是---')
        const { closeModal } = useModal.confirm({
          title: '请确认新发布的版本号和下载地址是否正确',
          content: h('div', {}, [
            h('p', '版本号:' + formData.number),
            h('p', '热更新包名:' + formData.address),
            h('p', '确保你已经修改了Hbuilder中manifest.json中版本号:' + formData.number)
          ]),
          onOk: async () => {
            // ios android同时热更新
            if (data.value.length == 2) {
              // 批量处理吗?Promise.all([p1,p2])
              data.value.forEach(async el => {
                formData.systemType = Number(el)

                let res = await addVersion(formData)
                if (res.success) {
                  message.success('添加成功')
                  data.visible = false
                  data.form = {}
                  data.form.updateType = 1
                  init()
                  closeModal()
                }
              })
            } else {
              data.form.systemType = Number(data.value[0])
              let res = await addVersion(data.form)
              if (res.success) {
                message.success('添加成功')
                data.visible = false
                data.form = {}
                data.form.updateType = 1
                init()
                closeModal()
              }
            }
          }
        })
      })
    }

    const cancel = () => {
      data.form = {
        updateType: 1,
        number: ''
      }
      // data.form.updateType = 1
      data.visible = false
    }

    // 新增
    const add = key => {
      data.visible = true
    }
    init()
    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...data.searchForm
      }
      let res = await selectAllVersion(obj)
      if (res.success) {
        res.object.records.map(el => (el.key = el.id))
        data.list = res.object.records
        page.total = res.object.total
        loading.value = false
      }
    }
    return {
      ...toRefs(data),
      formRef,
      // form,
      rules,
      columns,
      loading,
      pagination,
      handleTableChange,
      add,
      options,
      cancel,
      labelCol: { style: { fontWeight: 'bolder', width: '100px' } },
      save,
      tinymceInput,
      ports,
      panelChange,
      search
    }
  }
}
</script>
<style scoped lang="less">
.warning {
  padding: 5px 10px;
  font-size: 20px;
}
</style>
